<template>
  <div class="customer_page">
    <main>
      <div class="list-box" ref="listBox">
        <div class="list" v-for="item in list" :key="item.id">
          <div class="time">{{ new Date(item.time).toLocaleString() }}</div>
          <div :class="[item.dir === 1 ? 'list-item2' : 'list-item1']">
            <img
              :src="item.dir === 1 ? item.user_avatar : item.server_avatar"
              class="head-img"
            />
            <div class="msg-box">
              <p class="msg" v-if="item.type === 'text'">
                {{ stringToEmoji(item.message) }}
              </p>
              <el-image
                v-if="item.type === 'image'"
                class="msg-img"
                :src="item.message"
                :preview-src-list="[item.message]"
              />
              <video
                v-if="item.type === 'video'"
                :src="item.message"
                class="msg-video"
                controls
              ></video>
            </div>
          </div>
        </div>

        <!-- <div class="list">
          <div class="time">{{ new Date().toLocaleString() }}</div>
          <div class="list-item1">
            <img
              src="https://img2.baidu.com/it/u=1001860741,127553111&fm=253&app=120&size=w931&n=0&f=JPEG&fmt=auto?sec=1730221200&t=0e6d25eaf18ec1e540ae55ca98afc0c5"
              class="head-img"
            />
            <div class="msg-box">
              <p class="msg">这是一段文字内容</p>
              <img
                class="msg-img"
                src="https://img2.baidu.com/it/u=2062656537,1277924993&fm=253&app=120&size=w931&n=0&f=JPEG&fmt=auto?sec=1730221200&t=c026a30c38f5e343f06988f54a909773"
              />
            </div>
          </div>
          <div class="list-item2">
            <img
              src="https://img2.baidu.com/it/u=1001860741,127553111&fm=253&app=120&size=w931&n=0&f=JPEG&fmt=auto?sec=1730221200&t=0e6d25eaf18ec1e540ae55ca98afc0c5"
              class="head-img"
            />
            <div class="msg-box">
              <p class="msg">这是一段文字内容</p>
              <img
                class="msg-img"
                src="https://img2.baidu.com/it/u=2062656537,1277924993&fm=253&app=120&size=w931&n=0&f=JPEG&fmt=auto?sec=1730221200&t=c026a30c38f5e343f06988f54a909773"
              />
            </div>
          </div>
        </div> -->
      </div>
    </main>
    <footer>
      <div class="bot-top">
        <div class="emoji" v-show="emojiShow">
          <ul>
            <li
              v-for="item in emojiList"
              :key="item.rule"
              @click="handleEmojiChose(item)"
            >
              {{ item.content }}
            </li>
          </ul>
        </div>
        <span @click="handleEmojiShow" style="cursor: pointer">😀</span>
        <el-icon @click="handleIcon" style="cursor: pointer"
          ><Picture
        /></el-icon>
        <input
          ref="inputUpload"
          type="file"
          class="file-btn"
          @change="handleFileUpload"
        />
      </div>
      <el-input
        v-model="textarea"
        style="width: 100%"
        :rows="5"
        type="textarea"
        placeholder="Please input"
      />
      <el-button type="primary" class="btn" @click="handleSendBtn"
        >发送</el-button
      >
    </footer>
  </div>
</template>
<script setup>
import { nextTick, ref } from "vue";
import { emojiList, stringToEmoji, emojiToString } from "./emojiList";
import OSS from "ali-oss";

const textarea = ref("");
const list = ref([]);
const listBox = ref("");
const emojiShow = ref(false);
const inputUpload = ref(null);

const props = defineProps({
  id: "",
});
const socket = new WebSocket(
  `ws://124.221.74.149:8003/koa/ws?user_id=2&server_id=${props.id}`
);

// Connection opened
socket.addEventListener("open", function (event) {
  socket.send(JSON.stringify({ type: "getChatList" }));
});

// Listen for messages
socket.addEventListener("message", function (event) {
  console.log(JSON.parse(event.data), "===data");
  const data = JSON.parse(event.data);

  switch (data.type) {
    case "getChatList":
      list.value = data.data;
      nextTick(() => {
        listBox.value.scrollTop = listBox.value.scrollHeight;
      });
      break;
    case "addMessage":
      list.value.push(data.data);
      nextTick(() => {
        listBox.value.scrollTop = listBox.value.scrollHeight;
      });
  }
});

// 点击发送按钮发送信息
const handleSendBtn = () => {
  if (textarea.value.trim()) {
    socket.send(
      JSON.stringify({
        type: "addMessage",
        data: {
          user_id: 2,
          server_id: props.id,
          type: "text",
          message: emojiToString(textarea.value),
        },
      })
    );
    textarea.value = "";
  }
};

// 点击按钮显示隐藏表情包
const handleEmojiShow = () => {
  emojiShow.value = !emojiShow.value;
};

const handleEmojiChose = (item) => {
  textarea.value += item.content;
  emojiShow.value = false;
};

const handleIcon = () => {
  inputUpload.value.click();
};

const client = new OSS({
  // yourRegion填写Bucket所在地域。以华东1（杭州）为例，yourRegion填写为oss-cn-hangzhou。
  region: "oss-cn-beijing",
  // 从STS服务获取的临时访问密钥（AccessKey ID和AccessKey Secret）。
  accessKeyId: "LTAI5tMQbybx4w6ckMUAdnqu",
  accessKeySecret: "tfsV80jLce0Ib86nPbY4wfKUv5belC",
  // 填写Bucket名称。
  bucket: "biefan-test1",
});

const handleFileUpload = async (e) => {
  const file = e.target.files[0];
  // 上传阿里云
  const result = await client.put(file.name, file);
  const fileType = "";
  // 区分图片和视频
  // if (/image\/(jpe?g|png|gif|webp|gif)/.test(file.type)) {
  //  fileType = "image";
  // } else {
  //   fileType = "video";
  // }
  if (file.type.split("/")[0] === "image") {
    fileType = "image";
  } else {
    fileType = "video";
  }
  socket.send(
    JSON.stringify({
      type: "addMessage",
      data: {
        user_id: 2, // 自己id
        server_id: props.id, // 客服id
        type: fileType, // 发送类型
        message: result.url, // 文本域的值
      },
    })
  );
};
</script>

<style lang="scss" scoped>
.customer_page {
  width: 100%;
  height: 600px;
  ::-webkit-scrollbar {
    display: none;
  }

  main {
    height: 400px;

    .list-box {
      height: 400px;
      //滚动条
      overflow-y: scroll;

      .list {
        //准备内容翻转
        display: flex;
        flex-direction: column;
        margin-bottom: 10px;
        .time {
          text-align: center;
        }

        .list-item1,
        .list-item2 {
          display: flex;
          .head-img {
            width: 40px;
            height: 40px;
            border-radius: 50%;
          }
          .msg-box {
            margin: 0 8px;

            .msg {
              background-color: #ccc;
              padding: 10px;
              border-radius: 10px;
            }
            .msg-img {
              width: 150px;
              height: 150px;
              border-radius: 10px;
              margin-top: 5px;
            }
            .msg-video {
              width: 200px;
              height: 200px;
              margin-top: 5px;
            }
          }
        }
        .list-item2 {
          //水平方向旋转
          flex-direction: row-reverse;
          .msg-box {
            margin: 0 8px;

            .msg {
              background-color: #237ade;
              color: #fff;
              padding: 10px;
              border-radius: 10px;
            }
          }
        }
      }
    }
  }

  footer {
    position: relative;
    height: 200px;
    border-top: 1px #ccc solid;
    position: relative;

    .bot-top {
      height: 35px;
      display: flex;
      align-items: center;
      .emoji {
        position: absolute;
        top: -200px;
        left: 0;
        width: 250px;
        height: 200px;

        ul {
          height: 100%;
          display: flex;
          flex-wrap: wrap;
          border: 1px solid #ccc;
          background: pink;

          li {
            padding: 15px;
          }
        }
      }

      .el-icon {
        font-size: 20px;
        margin: 0 8px;
      }
      .file-btn {
        display: none;
      }
    }
    .btn {
      position: absolute;
      // top: 0;
      left: 0;
      bottom: 0;
      right: 0;
    }
  }
}
</style>